package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.Arrays;

/**
 * <a href="https://leetcode.cn/problems/partition-equal-subset-sum/?envType=study-plan-v2&envId=top-100-liked">416. 分割等和子集</a>
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode089 {
    public static void main(String[] args) {
        HotCode089 hotCode = new HotCode089();
        int[] nums = {23,13,11,7,6,5,5};
        System.out.println(hotCode.canPartition(nums));
    }

    public boolean canPartition(int[] nums) {
        int sum = Arrays.stream(nums).sum();
        if (sum % 2 == 1) {
            return false;
        }
        int half = sum >> 1;
        boolean[] dp = new boolean[half + 1];
        dp[0] = true;
        Arrays.sort(nums);
        for (int index = 0, balance; index < nums.length; index++) {
            for (balance = half; balance >= nums[index]; balance--) {
                if (!dp[balance] && balance - nums[index] >= 0) {
                    dp[balance] = dp[balance - nums[index]];
                    if (dp[half]) {
                        return true;
                    }
                }
            }
        }
        return dp[half];
    }
}